# -*- coding: utf-8 -*-

from plugmgr import plugin
import os

__all__ = ["lang"]

class lang(plugin):
    ''' This class provides methods to internationalize other plugins as well '''
    requires = ['config']
    loaded = {}
    def __init__(self,bot):
        self.bot = bot
    def add(self,filename):
        '''
        Load translations from i18n file.
        There's no exception handling! Be careful
        '''
        if filename in self.loaded:
            raise ValueError, 'i18n file is already loaded!'
        self.loaded[filename] = eval(''.join(file(os.path.join(self.bot.config.lang_dir,filename)).readlines()))
    def remove(self,filename):
        ''' Unload translations loaded from file '''
        del self.loaded[filename]
    def _get(self,message,lang):
        for i in self.loaded.values():
            if (lang in i.keys()) and (message in i[lang].keys()):
                return i[lang][message]
        raise ValueError, 'Not found'
    def get(self,message,lang,default=None):
        ''' Get message translated in language
        example of lang is "ua, ru, en"
        default is the message returned when no translation is found
        '''
        langs = map(
             # allow to use spaces in list
            lambda x: x.strip().lower(),
                lang.split(','))
        # \todo: удалить повторения из списка
        for l in langs:
            try:               return self._get(message,l)
            except ValueError: pass
        if default is not None:
            return default
        return message
    def detectLanguage(self, message):
        try:
            return message.getAttribute(("http://www.w3.org/XML/1998/namespace", "lang"), None).split('-')[0] # TODO: None has no split()!
        except:
            return None
